package com.college.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.college.commonutil.result.Result;
import com.college.eduService.entity.EduCourse;
import com.college.eduService.service.EduCourseService;
import com.college.order.service.TOrderService;
import com.college.order.service.TPayLogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/eduorder/t-pay-log")
@CrossOrigin
public class TPayLogController {

    @Autowired
    private TPayLogService tPayLogService;
    @Autowired
    private EduCourseService courseService;
    @Autowired
    private TOrderService orderService;

    //根据订单号，生成微信支付二维码的接口
    @GetMapping("/createWxQRcode/{orderNo}")
    public Result createWxQRcode(@PathVariable String orderNo){
        //返回信息，包含二维码地址、其他信息
        Map<String, Object> map = tPayLogService.createWxQrcode(orderNo);
        return Result.ok().data(map);
    }
    //根据订单号查询订单支付状态
    @GetMapping("/queryPayStatus/{orderNo}")
    public Result queryPayStatus(@PathVariable String orderNo){

        Map<String,String> map = tPayLogService.queryPayStatus(orderNo);
        if (map==null){
            return Result.error().message("支付出错了");
        }
        //如果返回的map不为空，通过map获取订单的状态
        if (map.get("trade_state").equals("SUCCESS")){ //支付成功
            //添加记录到支付表里，并更新订单表的状态
            tPayLogService.updateOrderStatus(map);
            //更新购买量
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.eq("order_no",orderNo);
            String courseId=orderService.getOne(wrapper).getCourseId();
            EduCourse course=courseService.getById(courseId);
            if(course!=null) {
                if (course.getBuyCount() == null) {
                    course.setBuyCount(0L);
                }
                course.setId(courseId);
                course.setBuyCount(course.getBuyCount() + 1L);
                courseService.updateById(course);
            }
            return Result.ok().message("支付成功");
        }

        return Result.ok().message("支付中").code(25000);
    }

}
